package com.scalar.chiptrack.operations.reports.actions;

import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.operations.reports.forms.ProductionReportByMonthForm;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * User: Sujan
 * Date: May 15, 2008
 * Time: 1:21:18 PM
 */
public class ProductionReportByMonthReportAction extends ChipTrackExtendedAction
{

    public ActionForward executeRequest(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String action = request.getParameter( "action" );
        ProductionReportByMonthForm productionReportByMonthForm = (ProductionReportByMonthForm)form;

        ArrayList productionReportDetailsList = null;
        Workbook workbook = null;
        String fileName = "";

        if ( action == null || "".equals(action) )
        {
            action = "productionReportByMonth";
        }
        try
        {
            if ( "productionReportByMonth".equalsIgnoreCase(action))
            {
                request.setAttribute( "monthList", DateUtil.getMonthsList() );
                request.setAttribute( "yearList", DateUtil.getYearList() );
                Calendar cal = Calendar.getInstance();
                productionReportByMonthForm.setMonth( cal.get( Calendar.MONTH )+1);
                productionReportByMonthForm.setYear( cal.get( Calendar.YEAR ));
                return mapping.findForward( "productionReportByMonth");
            }
            else if ( "generateProductionReportByMonthXls".equalsIgnoreCase( action ) )
            {
                productionReportDetailsList = NewProductDAO.loadProductionReportByMonthDetails( null,productionReportByMonthForm.getMonth(),productionReportByMonthForm.getYear());
                workbook =  DataDumpReportsHelper.getWorkbook( productionReportDetailsList, "Production Report By Month", null,null,null );
                fileName = "ProductionReportByMonth_"+DateUtil.getMonthsArray()[productionReportByMonthForm.getMonth()-1]+"_"+productionReportByMonthForm.getYear();

                ExcelUtils.generateExcelReport( workbook, fileName, response);
            }
        }
        catch ( Exception e)
        {
            //errors.put ( "Could not generate excel file", null );
            e.printStackTrace();
        }
        return null;
    }
}
